package com.anrong.wulansdk.sdk.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.anrong.gson.Gson;
import com.anrong.gson.GsonBuilder;
import com.anrong.orm.db.assit.QueryBuilder;
import com.anrong.wulansdk.sdk.db.LiteOrmDBUtil;
import com.anrong.wulansdk.sdk.entity.EventLog;
import com.anrong.wulansdk.sdk.interfaces.HttpListener;
import com.anrong.wulansdk.sdk.interfaces.WLHttpUtil;
import com.anrong.wulansdk.sdk.utils.MyLogcat;
import com.anrong.wulansdk.sdk.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 上传信息的服务
 * @author cxy
 *
 */
public class UploadService extends Service{
	private boolean isUploading = false;
	
	/**每次最多上传的条数*/
	private static final int MAX_COUNT = 10;
	/**超过此条数立马上传*/
//	private static final int UPLOAD_LESS_COUNT = 50;
	/**上传时间间隔 10秒*/
	private static final long UPLOAD_TIME = 10*1000;

	private Timer serviceTimer;  
	private TimerTask task;
	
	private Gson gson;
	
	private IBinder binder = new MyBinder(); 
	
	Handler handler = new Handler() {
		@Override  
		public void handleMessage(Message msg) {  

			//如果有网,并且不在上传中,开始上传信息
			if (Utils.isNetworkAvailable(UploadService.this)) {
				MyLogcat.log("isUploading :"+isUploading);
				if (!isUploading) {

					Utils.post(new Runnable() {
						@Override
						public void run() {
							uploadInfo();
						}
					});

				}
			}
		}  
	};
	private String json; 

	@Override
	public IBinder onBind(Intent intent) {
		MyLogcat.log("uploadService onBind");
		
		resetTimer();
		return binder;
	}
	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
//		try {
//			Thread.sleep(10*1000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		
		
	}


	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		MyLogcat.log("uploadService onStartCommand");
		resetTimer();

		return START_STICKY;
	}

	/**
	 * 重置定时任务
	 */
	public void resetTimer() {
		if (task != null) {
			task.cancel();
			task=null;
		}
		if (serviceTimer != null) {
			serviceTimer.cancel();
			serviceTimer = null;
		}
		task = new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(1);
			}
		};
		serviceTimer = new Timer();
		serviceTimer.schedule(task, 0, UPLOAD_TIME);
	}


	/**
	 * 判断数据库里是否有信息需要上传
	 * @return
	 */
	private boolean hasData() {
		if (LiteOrmDBUtil.getLiteOrm() == null) {
			LiteOrmDBUtil.createCascadeDB(UploadService.this);
		}
		long count = LiteOrmDBUtil.getLiteOrm().queryCount(EventLog.class);
		if (count > 0) {
			return true;
		}
		MyLogcat.log("no data need upload");
		return false;
	}

	/**
	 * 上传信息
	 */
	private synchronized void uploadInfo() {
		try {
			isUploading = true;

			MyLogcat.log("uploadInfo synchronized");
			if (!hasData()) {
				isUploading = false;
				return;
			}
			final List<EventLog> devices = LiteOrmDBUtil.getLiteOrm().query(new QueryBuilder(EventLog.class).limit(0, MAX_COUNT));
			//设置发送时间
//			for (UploadInfo d : devices) {
//				d.setSendTime(Utils.getCurrentUTCTime());
//			}
			
			//TODO 对象转json
//			ObjectMapper mapper = new ObjectMapper();
//			mapper.setSerializationInclusion(Include.NON_NULL);
//			json = mapper.writeValueAsString(devices);
			
			//gson
			if (gson == null) {
				gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
			}
			ArrayList<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
			Map<String, Object> map = null;
			for (EventLog d : devices) {
				map = new HashMap<String, Object>();
				/*map.put(UploadInfo.LOG_TYPE, d.getLogType());
				map.put(UploadInfo.APP_KEY, d.getAppKey());
				map.put(UploadInfo.DEVICE_ID, d.getDeviceId());
				map.put(UploadInfo.ACCOUNT_KEY, d.getAccountKey());
				map.put(UploadInfo.APP_VERSION, d.getAppVersion());
				map.put(UploadInfo.IP, d.getIp());
				map.put(UploadInfo.PLATFORM, d.getPlatform());
				map.put(UploadInfo.VENDOR, d.getVendor());
				map.put(UploadInfo.OS, d.getOs());
				map.put(UploadInfo.CARRIER, d.getCarrier());
				map.put(UploadInfo.NETWORK, d.getNetwork());
				map.put(UploadInfo.EVENT, d.getEvent());
				map.put(UploadInfo.EVENT_DESC, d.getEventDesc());
				map.put(UploadInfo.MAC, d.getMac());
				map.put(UploadInfo.MAPPING, d.getMapping());
				map.put(UploadInfo.MAPPING_DESC, d.getMappingDesc());
				map.put(UploadInfo.LONGITUDE, d.getLongitude());
				map.put(UploadInfo.LATITUDE, d.getLatitude());
				map.put(UploadInfo.ALTITUDE, d.getAltitude());
				map.put(UploadInfo.CITY, d.getCity());
				map.put(UploadInfo.PROVINCE, d.getProvince());
				map.put(UploadInfo.COUNTRY, d.getCountry());
				map.put(UploadInfo.RECORD_TIME, d.getRecordTime());
				map.put(UploadInfo.SEND_TIME, System.currentTimeMillis());*/

				map.put(EventLog.SID,d.getSid());//uuid
				map.put(EventLog.DEVID,d.getDevId());
				map.put(EventLog.USERID,d.getUserId());
				map.put(EventLog.APPCODE,d.getAppCode());
				map.put(EventLog.STAFFCODE,d.getStaffCode());
				map.put(EventLog.LATITUDE,d.getLatitude());
				map.put(EventLog.LONGITUDE,d.getLongitude());
				map.put(EventLog.ALTITUDE,d.getAltitude());
				map.put(EventLog.EVENTNAME,d.getEventName());
				map.put(EventLog.EVENTPATH,d.getEventPath());
				map.put(EventLog.EVENTDESC,d.getEventDesc());
				map.put(EventLog.STARTTIME,d.getStartTime());
				map.put(EventLog.ENDTIME,System.currentTimeMillis());
				map.put(EventLog.RESULT,d.getResult());
				map.put(EventLog.RESULTERR,d.getResultErr());

				list.add(map);
			}
			json = gson.toJson(list);
			
			
			MyLogcat.log(json);
			
			if (json.length() != 0) {
//				WLHttpUtil.post(json, new StringCallback() {
//					@Override
//					public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
//						if (arg3.code() == 200) {
//							MyLogcat.log("uploadService: "+arg1);
//							int delete = LiteOrmDBUtil.getLiteOrm().delete(devices);
//							MyLogcat.log("delete list :" + delete);
//						}
//						isUploading = false;
//					}
//					
//					@Override
//					public void onError(boolean isFromCache, Call call,
//							Response response, Exception e) {
//						isUploading = false;
//						super.onError(isFromCache, call, response, e);
//					}
//				});
				
				
				WLHttpUtil.postJson(json, new HttpListener() {
					
					@Override
					public void onSuccess(String result) {
						MyLogcat.log("uploadService: "+result);
						int delete = LiteOrmDBUtil.getLiteOrm().delete(devices);
						MyLogcat.log("delete list :" + delete);
						isUploading = false;
					}
					
					@Override
					public void onFail(Exception e) {
						isUploading = false;
					}
				});
				
				
			}else {
				isUploading = false;
			}
		} catch (Exception e) {
			isUploading = false;
			e.printStackTrace();
		}
	}

	@Override
	public void onDestroy() {
		if (serviceTimer != null) {
			serviceTimer.cancel();
		}
		isUploading = false;
		MyLogcat.log("uploadService destroy, isUploading:"+isUploading);
		super.onDestroy();
	}
	
	
	public class MyBinder extends Binder{
		public UploadService getService(){
			return UploadService.this;
		}
	}
	
	
	
}
